package logic

import (
	"context"
	"errors"
	"pa/cache"
	"pa/models/mysql"
	"time"

	"pa/parpc/internal/svc"
	"pa/parpc/parpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type GoodCarAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGoodCarAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GoodCarAddLogic {
	return &GoodCarAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GoodCarAddLogic) GoodCarAdd(in *parpc.GoodCarAddRequest) (*parpc.GoodCarAddResponse, error) {
	// todo: add your logic here and delete this line
	var findGoodCar mysql.GoodCar
	mysql.DB.Debug().Where("num=?,title=?", in.Num, in.Title).Find(&findGoodCar)
	if in.Num <= 0 {
		return nil, errors.New("库存不足,不允许添加到购物车")
	}

	goodCar := mysql.GoodCar{
		GoodId: int(in.GoodId),
		Title:  in.Title,
		Price:  float64(in.Price),
		Num:    int(in.Num),
	}
	mysql.DB.Debug().Create(&goodCar)
	cache.Rdb.Set(l.ctx, "goodCar", goodCar, time.Minute*3)

	return &parpc.GoodCarAddResponse{
		GoodCarId: int64(goodCar.ID),
	}, nil
}
